# encoding: utf-8
import os

import pyautogui
import cv2
import numpy as np
from PIL import ImageGrab, Image, ImageFont, ImageDraw
import time
import win32com.client as win32
import time

im1 = ImageGrab.grab()  # 截屏操作 默认全屏

class ImageUtil:
    def __init__(self):
        try:
            os.mkdir('D:\\automobile_config')
        except:
            pass
        try:
            os.mkdir('D:\\automobile_config\\auto_img_tmp')
        except:
            pass

    @classmethod
    def find(cls,src):
        cls.getScreen()
        target0 = cls.mathc_img(src)
        return target0

    @classmethod
    def findgood(cls,src,rate=0.99):
        cls.getScreen()
        target0 = cls.mathc_img(src,"screen", value=rate)
        return target0

    @classmethod
    def findmore(cls,src):
        cls.getScreen()
        targets = cls.mathc_more_img(src)
        return targets
    @classmethod
    def mergeone(cls,resarr,direction="y"):
        allpoint = []
        if direction == "y":
            y = 0
            for i in range(0,len(resarr)):
                if y == 0 or resarr[i][1] != y:
                    y = resarr[i][1]
                    allpoint.append(resarr[i])
            return allpoint
        else:
            x = 0
            for i in range(0, len(resarr)):
                if x == 0 or resarr[i][0] != x:
                    x = resarr[i][0]
                    allpoint.append(resarr[i])
            return allpoint
    @classmethod
    def click(cls,src,action="left"):
        target0 = cls.find(src)
        if action == "left":
            pyautogui.click(target0)
        else:
            if target0 != None and target0 != (0,0):
                pyautogui.click(target0[0],target0[1],button='right')

    @classmethod
    def pointclick(cls,src):
        target0 = cls.find(src)
        pyautogui.click(target0[0],target0[1])

    @classmethod
    def getScreen(cls):
        time.sleep(1)
        img_screen = ImageGrab.grab()
        img_screen.save("D:\\automobile_config\\auto_img_tmp\\screen.png")
        return "D:\\automobile_config\\auto_img_tmp\\screen.png"

    @classmethod
    def Screenshot(cls, filename):
        try:
            os.mkdir('D:\\FullService')
        except:
            pass
        try:
            os.mkdir('D:\\FullService\\Screenshot')
        except:
            pass
        time.sleep(1)
        img_screen = ImageGrab.grab()
        img_screen.save(f"D:\\FullService\\Screenshot\\{filename}.png")
        return f"D:\\FullService\\Screenshot\\{filename}.png"

    @classmethod
    def mathc_img(cls,image, Target="screen", value=0.9):
        if Target == "screen":
            img_rgb = cv2.imread("D:\\automobile_config\\auto_img_tmp\\screen.png")
        else:
            img_rgb = cv2.imread(Target)

        img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
        template = cv2.imread(image, 0)
        w, h = template.shape[::-1]
        res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
        threshold = value
        loc = np.where(res >= threshold)
        point = []
        for pt in zip(*loc[::-1]):
            #cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (7, 249, 151), 2)
            x = pt[0] + w/2
            y = pt[1] + h/2
            return (x,y)

    @classmethod
    def mathc_more_img(cls,image, Target="screen", value=0.9):
        if Target == "screen":
            img_rgb = cv2.imread("D:\\automobile_config\\auto_img_tmp\\screen.png")
        else:
            img_rgb = cv2.imread(Target)

        template = cv2.imread(image)
        w = template.shape[1]
        h = template.shape[0]
        res = cv2.matchTemplate(img_rgb, template, cv2.TM_CCOEFF_NORMED)
        threshold = value
        loc = np.where(res >= threshold)
        point = []
        for pt in zip(*loc[::-1]):
            #cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (7, 249, 151), 2)
            x = pt[0] + w/2
            y = pt[1] + h/2
            point.append((x,y))
        return point


    @classmethod
    def cropArea(cls,x1,y1,x2,y2):
        try:
            os.mkdir('D:\\tf')
        except:
            pass
        time.sleep(0.5)
        img_screen = ImageGrab.grab()
        im_path = img_screen.crop((x1, y1, x2, y2))
        DesignatedImg_path = "D:\\tf\\corp_area.png"
        im_path.save(DesignatedImg_path)
        return DesignatedImg_path

    @classmethod
    def alarm_find(cls,image):
        area = cls.cropArea(115,245,341,1028)
        time.sleep(1)
        result = cls.mathc_img(image,Target= area , value= 0.90)
        if result != None:
            result1 = result[0] + 115
            result2 = result[1] + 245
            return (result1, result2)
        else:
            return None

    @classmethod
    def image_show(cls,src):
        img = cv2.imread(src)
        cv2.imshow("img",img)
        cv2.waitKey(0)
        cv2.destroyAllWindows()

    @classmethod
    def excel_to_image(cls,src,dest,sheetname,area="A1:U67"):
        excel = win32.Dispatch('Excel.Application')
        wb = excel.Workbooks.Open(src)

        ws = wb.WorkSheets(sheetname)
        ws.Range(area).CopyPicture()
        ws.Paste()  # 变成图片

        # new_shape_name = 'shape_name_tmp' #通过名称定位图片
        # excel.Selection.ShapeRange.Name = new_shape_name #图片的重命名
        # ws.Shapes(new_shape_name).Copy() #图片至剪贴板
        ws.Shapes(ws.Shapes.Count).Copy()  # 图片至剪贴板
        img = ImageGrab.grabclipboard()
        img.save(dest)
        wb.Save()
        wb.Close()

    @classmethod
    def text_to_image(cls,text,dst):
        im = Image.new("RGB", (300, 50), (255, 255, 255))
        dr = ImageDraw.Draw(im)
        font = ImageFont.truetype("C:\\WINDOWS\\Fonts\simsun.ttc", 18)

        dr.text((10, 5), text, font=font, fill="#000000")
        now = time.strftime('%Y%m%d%H%M%S')
        im.save(dst)
